﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QldtSdh.BLL;
using QldtSdh.GUI.Utils;

namespace QldtSdh.GUI.NCS
{
    using BLL;
    using DAL;
    using DAL.Models;
    using QldtSdh.Utils;
    using QldtSdh.GUI.Utils;
    using System.Net.Mail;
    using System.Net;
    using QldtSdh.GUI.Common;
    using System.Configuration;

    public partial class FormQuanLyHoSoNCS : QldtSdh.GUI.Common.BaseDialog
    {
        private bool allowUpdate = false;
        public FormQuanLyHoSoNCS()
        {
            InitializeComponent();
            gridNCS.AutoGenerateColumns = false;
            LoadKhoaHoc();
            LoadNganhDaoTao();
            LoadNghienCuuSinh();
            gridNCS.SetDataGridViewAsReadonly(rowHeadersVisible: true, columnHeadersVisible: true);
            gridNCS.ReadOnly = false;
            gridNCS.AddRowIndexing();
        }

        void LoadKhoaHoc()
        {
            allowUpdate = false;
            var ls = BizKhoaHocNCS.GetList();
            ls.Insert(0, new KhoaHocNCS { NamTuyenSinh = -1, TenKhoaHoc = "Tất cả", MaKhoaHocNCSGUID = "-1" });
            cbxKhoaDaoTao.DataSource = ls;
            cbxKhoaDaoTao.DisplayMember = "TenKhoaHoc";
            cbxKhoaDaoTao.ValueMember = "MaKhoaHocNCSGUID";
            allowUpdate = true;
        }

        void LoadNganhDaoTao()
        {
            allowUpdate = false;
            var ls = BizChuyenNganhDaoTaoNCS.GetList();
            ls.Insert(0, new NganhDaoTaoNCS { MaNganhDaoTaoNCSGUID = "-1", TenNganhDaoTao = "Tất cả" });
            cbxNganh.DataSource = ls;
            cbxNganh.DisplayMember = "TenNganhDaoTao";
            cbxNganh.ValueMember = "MaNganhDaoTaoNCSGUID";
            allowUpdate = true;
        }

        void LoadNghienCuuSinh()
        {
            allowUpdate = false;
            var ls = BizNghienCuuSinh.GetList(cbxKhoaDaoTao.SelectedValue.ToString(), cbxNganh.SelectedValue.ToString());
            bsNCS.DataSource = ls;
            gridNCS.DataSource = bsNCS;
            allowUpdate = true;
        }


        private void btnThem_Click(object sender, EventArgs e)
        {
            var khoa = cbxKhoaDaoTao.SelectedItem as KhoaHocNCS;
            var nganh = cbxNganh.SelectedItem as NganhDaoTaoNCS;
            //if (khoa.MaKhoaHocNCSGUID == "-1" || nganh.MaNganhDaoTaoNCSGUID == "-1")
            //    return;
            var fdg = new FormQuanLyHocVien_ChiTiet(khoa, nganh);
            fdg.OnChanged += (o, t) =>
            {
                LoadNghienCuuSinh();
            };
            fdg.ShowDialog();
        }


        private void btnSua_Click(object sender, EventArgs e)
        {
            var khoa = cbxKhoaDaoTao.SelectedItem as KhoaHocNCS;
            var nganh = cbxNganh.SelectedItem as NganhDaoTaoNCS;
            var ncs = bsNCS.Current as NghienCuuSinh;
            if (ncs == null)
                return;
            var fdg = new FormQuanLyHocVien_ChiTiet(khoa, nganh, ncs);
            fdg.OnChanged += (o, t) =>
            {
                LoadNghienCuuSinh();
            };
            fdg.ShowDialog();
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var current = bsNCS.Current as NghienCuuSinh;
            if (current != null)
            {
                if (DialogUtils.ShowOKCancel(NOTIFY_CONSTANT_STRING.DELETE) == System.Windows.Forms.DialogResult.OK)
                {
                    var rs = BizNghienCuuSinh.Delete(current.MaNCSGUID);
                    if (rs == CODE_RESULT_RETURN.ThanhCong)
                    {
                        bsNCS.RemoveCurrent();
                        gridNCS.Refresh();
                    }
                    else
                        DialogUtils.ShowError(string.Format(ERROR_CONSTANT_STRING.LOI_XOA, ENTITY_NAME.NGHIENCUUSINH));
                }
            }
        }

        private void lnkFilter_Click(object sender, EventArgs e)
        {
            //pnlFilterContainter.Visible = !pnlFilterContainter.Visible;
            //if (pnlFilterContainter.Visible == false)
            //    ; // bsDeTai.RemoveFilter();
            gridNCS.EndEdit();
            btnSend_Click(null, null);
        }

        private void gridDeTai_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (this.SelectedDeTai != null)
            //    btnSua_Click(null, null);
        }

        private void lnkKhoaDaoTao_Click(object sender, EventArgs e)
        {
            var fdg = new FormQuanLyKhoaHoc();
            if (fdg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                LoadKhoaHoc();
        }

        private void lnkNganh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var fdg = new FormQuanLyNganhDaoTao();
            if (fdg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                LoadNganhDaoTao();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            #region Thu thập email của các NCS
            var ls = bsNCS.DataSource as MySortableBindingList<NghienCuuSinh>;
            var lstReceiver = new List<NghienCuuSinh>();
            foreach (var x in ls)
                if (x._IsSelected)
                    lstReceiver.Add(x);
            if (lstReceiver.Count == 0)
            {
                DialogUtils.ShowErrorWithDefaultTitle("Hãy đánh dấu chọn vào ít nhất một dòng trong danh sách rồi thực hiện gửi thư");
                return;
            }
            var frm = new FormSendMailToNCS(lstReceiver);
            frm.ShowDialog(this);
            #endregion
        }

        void SendMail(string subject, string body, string emailTo,
            string email, string emailPassword, string smtpAddress = "smtp.gmail.com", int portNumber = 587, bool enableSSL = true)
        {
            //string smtpAddress = "smtp.gmail.com";
            string emailFrom =
                //ConfigurationManager.AppSettings["email"];
                email;
            string password =
                //ConfigurationManager.AppSettings["pass"];
                emailPassword;
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(emailFrom);
                mail.To.Add(emailTo);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;

                //mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
                //mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));

                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(emailFrom, password);
                    smtp.EnableSsl = enableSSL;
                    smtp.Send(mail);
                }
            }
        }

        void SendMail(string subject, string body, List<string> lstMailAddressToReceive,
            string email, string emailPassword, string smtpAddress = "smtp.gmail.com", int portNumber = 587, bool enableSSL = true)
        {
            //string smtpAddress = "smtp.gmail.com";
            string emailFrom =
                //ConfigurationManager.AppSettings["email"];
                email;
            string password =
                //ConfigurationManager.AppSettings["pass"];
                emailPassword;
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(emailFrom);
                foreach (var x in lstMailAddressToReceive)
                    mail.To.Add(x);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;

                //mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
                //mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));

                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(emailFrom, password);
                    smtp.EnableSsl = enableSSL;
                    smtp.Send(mail);
                }
            }
        }

        private void cbxKhoaDaoTao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (allowUpdate)
                LoadNghienCuuSinh();
        }

        private void cbxNganh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (allowUpdate)
                LoadNghienCuuSinh();
        }

        private void bsNCS_CurrentChanged(object sender, EventArgs e)
        {
            var current = bsNCS.Current as NghienCuuSinh;
            if (current != null)
            {
                btnSua.Enabled = btnSua.Enabled = true;
                NghienCuuSinh_PropertyGrid ncsProperty = new NghienCuuSinh_PropertyGrid()
                {
                    DiaChi = current.DiaChi,
                    Email = current.Email,
                    GioiTinh = current._GioiTinhStr,
                    HoTen = current.HoTen,
                    KhoaHoc = current._KhoaHoc,
                    NganhHoc = current._NganhHoc,
                    NgaySinh = current.NgaySinh,
                    NoiSinh = current.NoiSinh,
                    QuocTich = current.QuocTich,
                    SoDienThoai = current.SoDienThoai
                };
                propertyGridHocPhan.SelectedObject = ncsProperty;
            }
            else
            {
                btnXoa.Enabled = false;
                propertyGridHocPhan.SelectedObject = null;
            }
        }
    }

    [DefaultPropertyAttribute("HoTen")]
    public class NghienCuuSinh_PropertyGrid
    {
        private const string A = "A. Thông tin chung";
        [CategoryAttribute(A), DisplayName("1. Họ tên")]
        public string HoTen { get; set; }
        [CategoryAttribute(A), DisplayName("2. Giới tính")]
        public string GioiTinh { get; set; }
        [CategoryAttribute(A), DisplayName("3. Ngày sinh")]
        public string NgaySinh { get; set; }
        [CategoryAttribute(A), DisplayName("4. Nơi sinh")]
        public string NoiSinh { get; set; }
        [CategoryAttribute(A), DisplayName("5. Địa chỉ")]
        public string DiaChi { get; set; }
        [CategoryAttribute(A), DisplayName("6. Quốc tịch")]
        public string QuocTich { get; set; }
        [CategoryAttribute(A), DisplayName("7. Số điện thoại")]
        public string SoDienThoai { get; set; }
        [CategoryAttribute(A), DisplayName("8. Email")]
        public string Email { get; set; }

        private const string B = "B. Thông tin  đào tạo";
        [CategoryAttribute(B), DisplayName("1. Khóa học")]
        public string KhoaHoc { get; set; }
        [CategoryAttribute(B), DisplayName("2. Ngành học")]
        public string NganhHoc { get; set; }

    }
}
